package com.ideafactory.client.ybservice.ybviewpager;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.ideafactory.client.afinal.NetConstants;
import com.ideafactory.client.beans.CatalogGoodsBean;
import com.ideafactory.client.beans.LeftGoodsBean;
import com.ideafactory.client.beans.PopGoodsList;
import com.ideafactory.client.beans.RightGoodsBean;
import com.ideafactory.client.utils.CommonUtils;
import com.ideafactory.client.utils.HintViewUtils;
import com.ideafactory.client.utils.JsonForBean;
import com.ideafactory.client.utils.SpUtils;
import com.ideafactory.client.utils.TYTool;
import com.ideafactory.client.utils.animationutils.CircleAnimationUtil;
import com.ideafactory.client.utils.netutils.MyCallBack;
import com.ideafactory.client.utils.netutils.NetUtils;
import com.ideafactory.client.views.BottomViewAdapter;
import com.ideafactory.client.views.CustomProgressDialog;
import com.ideafactory.client.views.DividerItemDecoration;
import com.ideafactory.client.views.GoodsEnsureAdapter;
import com.ideafactory.client.views.LeftViewAdapter;
import com.ideafactory.client.views.PointerPopupWindow;
import com.ideafactory.client.views.RightGridViewAdapter;

import com.ideafactory.client.ybselfservice.R;
import com.ideafactory.client.ybservice.APP;
import com.ideafactory.client.ybservice.AppActivityManager;
import com.ideafactory.client.ybservice.YbSelfService;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ideafactory.client.ybselfservice.R.id.rv_goods_ensure;


public class GoodsDetialPager extends GoodsBasePager {

    private static final String TAG = "GoodsDetialPager";


    public GoodsDetialPager(Context context) {
        super(context);
    }
    @Override
    public View initView() {
       View view = View.inflate(context, R.layout.pager_goods_detial,null);
       x.view().inject(this,view);
       return view;
    }

    @ViewInject(R.id.pager_left_view)
    private RecyclerView pager_left_view;

    @ViewInject(R.id.right_goods_view)
    private RecyclerView right_goods_view;

    @ViewInject(R.id.bottom_goods_view)
    private RecyclerView bottom_goods_view;

    //已选N件,总价money
    @ViewInject(R.id.tv_dinner_count_desc)
    private TextView tv_dinner_count_desc;

    @ViewInject(R.id.shop_cart_iamge)
    private ImageView shop_cart_iamge;

    @ViewInject(R.id.tv_bottom_des)
    private TextView tv_bottom_des;

    @ViewInject(R.id.ll_bottom_item)
    private LinearLayout ll_bottom_item;

    @ViewInject(R.id.tv_right_goods_view_hint)
    private TextView tv_right_goods_view_hint;

    @ViewInject(R.id.iv_no_goods)
    private ImageView iv_no_goods;

    @ViewInject(R.id.layout_right)
    private FrameLayout layout_right;

    @ViewInject(R.id.iv_lookdown)
    private ImageView iv_lookdown;


    @Override
    public void initViewBuind() {
        initLeftLayout();
        initRightLayout();
        initBottomLayout();
        setOnReceivedChangeMain(new OnReceivedChangeMain() {
            @Override
            public void changeToMain() {
                dissMissPop();
            }
        });
        initFromData();
    }

    private void initFromData() {

    }

    private CustomProgressDialog customProgressDialog;

    @Override
    public void initData(int fromPager) {
        if(fromPager!=GoodsBasePager.GOODS_ENSURE_INT){
            getNetLeftMenuData();
        }
        Log.i("goodsdetialpager", "initdata");
        List<CatalogGoodsBean> catalogGoodsBeans = (List<CatalogGoodsBean>) getObj(GOODS_ENSURE_INT);
            if(catalogGoodsBeans!=null && catalogGoodsBeans.size()>0){
                Log.d("detialpager界面","size大0");
                cartGoodsNum = 0;
                cartGoodsMoney = 0;
                int size = catalogGoodsBeans.size();
                for(int i=0;i<size;i++){
                    cartGoodsNum += catalogGoodsBeans.get(i).getGoodsAdded();
                    cartGoodsMoney = CommonUtils.addNum(cartGoodsMoney,CommonUtils.mulNum(catalogGoodsBeans.get(i).getPrice(), catalogGoodsBeans.get(i).getGoodsAdded()));
                }
                setMoneyCount();
                bottomViewAdapter.setCatalogGoodsLists(catalogGoodsBeans);
                bottomViewAdapter.notifyDataSetChanged();
            }else{
                Log.d("detialpager界面","size=0");
                cartGoodsNum = 0;
                cartGoodsMoney = 0;
                if(bottomViewAdapter!=null){
                    bottomViewAdapter.clearBottom();
                }
                setBottomVisible(false);
                setMoneyCount();
            }
    }

    LeftViewAdapter leftViewAdapter;
    private void initLeftLayout() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        pager_left_view.setLayoutManager(linearLayoutManager);
        leftViewAdapter = new LeftViewAdapter();
        pager_left_view.setAdapter(leftViewAdapter);
        leftViewAdapter.setOnItemClickLinster(new LeftViewAdapter.OnItemClickLinster() {
            @Override
            public void onItemClick(View view, int position) {
                if(mCurrentLeftPosition!=position){
                    Log.d("position","initLeftLayout"+mCurrentLeftPosition);

                    right_goods_view.setVisibility(View.GONE);
                    layout_right.setVisibility(View.GONE);
                    tv_right_goods_view_hint.setVisibility(View.VISIBLE);

                    getRightMenuData(position);
                }
            }
        });
    }

    /**
     * 按钮点击事件
     * @param view
     */
    @Event(value = {R.id.btn_cancle_order, R.id.btn_ok_order, R.id.btn_return_last}, type = View.OnClickListener.class)
    private void btn_click(View view) {
        if(null!=null && customProgressDialog.isShowing()){
            customProgressDialog.dismiss();
        }
        switch (view.getId()) {
            case R.id.btn_cancle_order:
                createDialog(context.getResources().getString(R.string.qdxxdd));
                break;
            case R.id.btn_ok_order:
                Map<String, Object> toNextMap = new HashMap<>();
                toNextMap.put("totalMoney",cartGoodsMoney);
                toNextMap.put("goodsData", bottomViewAdapter.getBottomData());
                setObj(GOODS_DETIAL_INT, toNextMap);
                onPagerChange.changePositon(GOODS_DETIAL_INT,GOODS_ENSURE_INT);
                break;
            case R.id.btn_return_last:
                clearObj();
                returnLast();
                break;
        }
    }

    private void returnLast() {
        onPagerChange.changePositon(GOODS_DETIAL_INT,MAIN_FRAGMENT);
    }

    private RightGridViewAdapter rightGridViewAdapter;
    /**
     * 初始化右边的布局
     */
    private void initRightLayout() {
        GridLayoutManager layoutManager = new GridLayoutManager(context, 2);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        right_goods_view.setLayoutManager(layoutManager);
        right_goods_view.addItemDecoration(new DividerItemDecoration(35));
        rightGridViewAdapter = new RightGridViewAdapter();
        right_goods_view.setAdapter(rightGridViewAdapter);
        //右侧item的点击事件
        rightGridViewAdapter.setOnItemClickLinster(new RightGridViewAdapter.OnItemClickLinster() {
            @Override
            public void onItemClick(View view, int position) {
                Log.d("position","rightGridViewAdapter"+position);
                dissMissPop();
                if (rightItems.get(position).getType() == 3) {
                    showPopupWindow(view, position);
                } else {
                    addDataToBottom(rightItems.get(position), view);
                }
            }
        });
    }

    /**
     * 获取网络连接数据
     */
    private void getNetLeftMenuData() {
        customProgressDialog = new CustomProgressDialog(context,"",R.drawable.frame);
        customProgressDialog.show();

        String modelId = SpUtils.getString(APP.getAPP().getApplicationContext(), SpUtils.MODELID, "");
        if (!TextUtils.isEmpty(modelId)) {
            Map liftMenu = new HashMap();
            liftMenu.put("modelId", modelId);
            NetUtils.Post(NetConstants.MODEL_CATALOG_LIST, liftMenu, new MyCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.e("result-left", result);
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        String status = (String) TYTool.getJsonObj(jsonObject, "status", "0");
                        if (status.equals("1")) {
                            initLeftMenu(result);
                        } else {
                            //该店铺无数据
                            iv_no_goods.setVisibility(View.VISIBLE);
                            Toast.makeText(context,APP.getAPP().getResources().getString(R.string.noGoods),Toast.LENGTH_SHORT).show();
                            customProgressDialog.dismiss();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e(TAG, "catch: " );
                        customProgressDialog.dismiss();
                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    customProgressDialog.dismiss();
                    Log.e(TAG, "onError: " );
                }
            });
        }
    }

    /**
     * 初始化左边视图
     */
    private List<LeftGoodsBean.CatalogList> catalogLists;
    private void initLeftMenu(String leftMenu) {
        LeftGoodsBean leftGoodsBean = JsonForBean.getPerson(leftMenu, LeftGoodsBean.class);
        catalogLists = leftGoodsBean.catalogList;
        leftViewAdapter.setCatalogLists(catalogLists);
        getRightMenuData(mCurrentLeftPosition);
    }

    private int mCurrentLeftPosition = 0;

    /**
     * 初始化右边视图
     * @param position
     */
    private void getRightMenuData(int position) {
        mCurrentLeftPosition = position;
        leftViewAdapter.setPosition(position);
        Map rightItem = new HashMap();
        Log.e(TAG, "catalogId--->"+catalogLists.get(position).catalogId );
        rightItem.put("catalogId", catalogLists.get(position).catalogId);
        NetUtils.Post(NetConstants.CATALOG_GOODS_LIST, rightItem,new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Log.e("result-right", result);
                        right_goods_view.setVisibility(View.GONE);
                        layout_right.setVisibility(View.GONE);
                        tv_right_goods_view_hint.setVisibility(View.VISIBLE);
                        loadRightMenuItem(result);
                    }
                });
    }

    /**
     * 加载右边的数据信息
     */
    private RightGoodsBean rightGoodsBean;
    private List<CatalogGoodsBean> rightItems;
    private PointerPopupWindow pointerPopupWindow;

    private void loadRightMenuItem(String rightMenu) {
        dissMissPop();
        rightGoodsBean = JsonForBean.getPerson(rightMenu, RightGoodsBean.class);
        rightItems = rightGoodsBean.getCatalogGoodsList();
        if (rightItems.size()>12){
            iv_lookdown.setVisibility(View.VISIBLE);
        }else {
            iv_lookdown.setVisibility(View.GONE);
        }


        if (rightItems!=null && rightItems.size()>0){
            right_goods_view.setVisibility(View.VISIBLE);
            layout_right.setVisibility(View.VISIBLE);
            tv_right_goods_view_hint.setVisibility(View.GONE);
            rightGridViewAdapter.setRightList(rightItems);

        }else{
            right_goods_view.setVisibility(View.GONE);
            layout_right.setVisibility(View.GONE);
            tv_right_goods_view_hint.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示的弹出框
     */
    private void showPopupWindow(final View basedView, final int position) {
        Map popUpMap = new HashMap();
        popUpMap.put("groupId", rightItems.get(position).getGoodsId());
        NetUtils.Post(NetConstants.GOODS_GROUP_LIST, popUpMap, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (!TextUtils.isEmpty(result)&& !result.equals("2")) {
                    Log.e(TAG, "result----------->"+result );
                    loadPop(basedView, result, position);
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                HintViewUtils.showMyToast(APP.getAPP().getResources().getString(R.string.DataFfailed),-1);
            }
        });

    }


    /**
     * 加载弹出框
     */
    private void loadPop(View basedView, String popResult,int location) {

        PopGoodsList popGoodsList = JsonForBean.getPerson(popResult, PopGoodsList.class);
        final List<CatalogGoodsBean> catalogGoodsLists = popGoodsList.getGoodsGroupList();

        View view = LayoutInflater.from(context).inflate(R.layout.popup_layout, null);
        RecyclerView recyclerpopView = (RecyclerView) view.findViewById(R.id.pop_layout_goods);

        GridLayoutManager layoutManager = new GridLayoutManager(context, 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerpopView.setLayoutManager(layoutManager);
        RightGridViewAdapter popWindowAdapter = new RightGridViewAdapter();
        popWindowAdapter.setRightList(catalogGoodsLists);
        popWindowAdapter.setIsPopAdapter(true);
        recyclerpopView.setAdapter(popWindowAdapter);
        popWindowAdapter.setOnItemClickLinster(new RightGridViewAdapter.OnItemClickLinster() {
            @Override
            public void onItemClick(View view, int position) {
                addDataToBottom(catalogGoodsLists.get(position),view);
            }
        });

        pointerPopupWindow = new PointerPopupWindow(APP.getAPP().getApplicationContext(), 800, 300);
        pointerPopupWindow.setPointerImageRes(R.mipmap.ic_popup_pointer_up);
        pointerPopupWindow.setContentView(view);

        //阴影遮罩
        ColorDrawable dw = new ColorDrawable(0x00000000);
        pointerPopupWindow.setBackgroundDrawable(dw);

        if(location%3==0){
            pointerPopupWindow.showAsPointer(basedView,30,0);
        }else if(location%3==1){
            pointerPopupWindow.showAsPointer(basedView,0,0);
        }else if(location%3==2){
            pointerPopupWindow.showAsPointer(basedView,0,0);
        }

        CommonUtils.backgroundAlpha(0.5f);
        pointerPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                CommonUtils.backAlpha(1.0f);
            }
        });
    }

    /**
     * 更新底部导航栏
     */
    private void addDataToBottom(CatalogGoodsBean catalogGoods,View view) {
        Log.e(TAG, "count------> "+catalogGoods.getCount() );
        if(bottomViewAdapter.getGoodsAdded(catalogGoods.getGoodsId())){
            if(catalogGoods.getCount()>0 || catalogGoods.getCount()==-1){
                setBottomVisible(true);
                CatalogGoodsBean shopGoods = new CatalogGoodsBean();
                shopGoods.setCount(catalogGoods.getCount());
                shopGoods.setPrice(catalogGoods.getPrice());
                shopGoods.setName(catalogGoods.getName());
                shopGoods.setDiscount(catalogGoods.getDiscount());
                shopGoods.setImageSrc(catalogGoods.getImageSrc());
                shopGoods.setUnit(catalogGoods.getUnit());
                shopGoods.setGoodsAdded(1);
                shopGoods.setIsPackCharge(catalogGoods.getIsPackCharge());
                shopGoods.setPackMoney(catalogGoods.getPackMoney());
                shopGoods.setGoodsId(catalogGoods.getGoodsId());
                bottomViewAdapter.addData(shopGoods);
                showAnimation(view);
            }else{
                HintViewUtils.showMyToast("", R.mipmap.goods_sold_out);
                Log.e(TAG, "count111111111111111------> "+catalogGoods.getCount() );
            }
        }else{
            Log.e(TAG, "count222222222222222------> "+catalogGoods.getCount() );
            HintViewUtils.showMyToast("", R.mipmap.goods_sold_out);
        }
    }
    /**
     * 更新底部导航栏
     */
    private void addDataToBottom2(CatalogGoodsBean catalogGoods) {
        Log.e(TAG, "count------> "+catalogGoods.getCount() );
        if(bottomViewAdapter.getGoodsAdded(catalogGoods.getGoodsId())){
            if(catalogGoods.getCount()>0 || catalogGoods.getCount()==-1){
                setBottomVisible(true);
                CatalogGoodsBean shopGoods = new CatalogGoodsBean();
                shopGoods.setCount(catalogGoods.getCount());
                shopGoods.setPrice(catalogGoods.getPrice());
                shopGoods.setName(catalogGoods.getName());
                shopGoods.setDiscount(catalogGoods.getDiscount());
                shopGoods.setImageSrc(catalogGoods.getImageSrc());
                shopGoods.setUnit(catalogGoods.getUnit());
                shopGoods.setGoodsAdded(catalogGoods.getGoodsCount());
                shopGoods.setIsPackCharge(catalogGoods.getIsPackCharge());
                shopGoods.setPackMoney(catalogGoods.getPackMoney());
                shopGoods.setGoodsId(catalogGoods.getGoodsId());
                bottomViewAdapter.addData(shopGoods);
            }else{
                HintViewUtils.showMyToast("", R.mipmap.goods_sold_out);
                Log.e(TAG, "count111111111111111------> "+catalogGoods.getCount() );
            }
        }else{
            Log.e(TAG, "count222222222222222------> "+catalogGoods.getCount() );
            HintViewUtils.showMyToast("", R.mipmap.goods_sold_out);
        }
    }


    /**
     * 购物车动画
     * @param fromView
     */
    private void showAnimation(View fromView) {
        CircleAnimationUtil util = new CircleAnimationUtil().attachActivity(AppActivityManager.getAppActivityManager().currentActivity()).setTargetView(fromView).setDestView(shop_cart_iamge);
        util.startAnimation();
    }

    /**
     * 初始化底部视图
     */
    private BottomViewAdapter bottomViewAdapter;
    private int cartGoodsNum;//订单的数量
    private double cartGoodsMoney;

    //初始化底部的布局
    private void initBottomLayout() {
        GridLayoutManager layoutManager = new GridLayoutManager(context, 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        bottom_goods_view.setLayoutManager(layoutManager);
        bottomViewAdapter = new BottomViewAdapter(context);
        bottom_goods_view.addItemDecoration(new DividerItemDecoration(15));
        bottom_goods_view.setAdapter(bottomViewAdapter);
        bottomViewAdapter.setOnreceiveBottomChange(new BottomViewAdapter.OnreceiveBottomChange() {
            @Override
            public void onAddMoney(double money) {
                ++cartGoodsNum;
                cartGoodsMoney = CommonUtils.addNum(cartGoodsMoney, money);
                setMoneyCount();
            }
            @Override
            public void onSubMoney(double money) {
                --cartGoodsNum;
                cartGoodsMoney = CommonUtils.subNum(cartGoodsMoney, money);
                setMoneyCount();
            }
            @Override
            public void bottomCleared() {
                setBottomVisible(false);
            }
            @Override
            public void itemAddInvalid() {//商品数量增加到最大值，不能继续添加
                HintViewUtils.showMyToast("", R.mipmap.goods_sold_out);
            }
        });
    }

    private void setMoneyCount(){
        tv_dinner_count_desc.setText(context.getResources().getString(R.string.yixuan)+ cartGoodsNum + context.getResources().getString(R.string.jian)+context.getResources().getString(R.string.money_unit)  + cartGoodsMoney);
    }

    AlertDialog.Builder builder ;
    AlertDialog dialog;
    public void createDialog(String msg){
        builder = new AlertDialog.Builder(context);
        dialog = builder.create();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = 450;
        params.height = 200 ;
        dialog.getWindow().setAttributes(params);

        View view = View.inflate(APP.getAPP().getApplicationContext(),R.layout.dialog_show_delete_goods,null);
        Button btn_ensure = (Button) view.findViewById(R.id.btn_ensure);
        Button btn_cancle = (Button) view.findViewById(R.id.btn_cancle);
        TextView tv_goods_name = (TextView) view.findViewById(R.id.tv_goods_name);

        tv_goods_name.setText(msg);

        btn_ensure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomViewAdapter.clearBottom();
                cartGoodsNum = 0;
                cartGoodsMoney = 0;
                setMoneyCount();
                dialog.dismiss();
                setBottomVisible(false);
            }
        });
        btn_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
    }

    //购物车有无购物信息的切换
    private void setBottomVisible(boolean isCartAdd){
        if(isCartAdd){
            if(tv_bottom_des.getVisibility() == View.VISIBLE){
                tv_bottom_des.setVisibility(View.GONE);
            }
            if(ll_bottom_item.getVisibility() != View.VISIBLE){
                ll_bottom_item.setVisibility(View.VISIBLE);
            }
        }else{
            tv_bottom_des.setVisibility(View.VISIBLE);
            ll_bottom_item.setVisibility(View.GONE);
        }
    }

    private void dissMissPop(){
        if(customProgressDialog!=null&&customProgressDialog.isShowing()){
            customProgressDialog.dismiss();
            customProgressDialog=null;
        }
        if (pointerPopupWindow != null && pointerPopupWindow.isShowing()) {
            pointerPopupWindow.dismiss();
        }
        if(bottomViewAdapter!=null){
            bottomViewAdapter.dismisPop();
        }

        if (dialog!=null&&dialog.isShowing()){
            dialog.dismiss();
        }
    }

    public interface OnReceivedChangeMain{
        void changeToMain();
    }
    public static OnReceivedChangeMain onReceivedChangeMain;
    public static void setOnReceivedChangeMain(OnReceivedChangeMain onReceivedChangeMain) {
        GoodsDetialPager.onReceivedChangeMain = onReceivedChangeMain;
    }

}
